package com.ibm.workplace.wcm.cqplugin.cqweb;

import com.ibm.httptest.apache.ApacheHTTPDriver;
import com.ibm.httptest.apache.RunScriptApache;
import com.ibm.httptest.driver.HTTPDriver;
import com.ibm.httptest.driver.HTTPPostData;
import com.ibm.httptest.html.HTMLManager;
import com.ibm.httptest.script.HTMLFailureException;
import com.ibm.httptest.script.ScriptProperties;
import com.ibm.httptest.script.TestFailureException;
import com.ibm.httptest.script.TestScript;

import org.apache.commons.httpclient.HttpClient;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Properties;

import com.ibm.httptest.Run;
import com.ibm.httptest.TestParameters;
import com.ibm.httptest.driver.HTTPDriver;
import com.ibm.httptest.html.HTMLManager;
import com.ibm.httptest.log.DefaultStatsWriter;
import com.ibm.httptest.log.StatisticsWriter;
import com.ibm.httptest.script.ScriptProperties;
import com.ibm.httptest.script.TestScript;

import com.ibm.workplace.wcm.cqplugin.*;
import com.ibm.workplace.wcm.cqplugin.cq.*;
import com.ibm.workplace.wcm.cqplugin.preference.*;

import java.util.*;

//import com.ibm.workplace.wcm.cqplugin.util.*;


public class CQHttpTest {
	
	final static String idString = "Defect_ID";
	final static String headString = "Headline";
	final static String submitterString = "Submitter";
	final static String severityString = "Severity";
	final static String stateString = "State";
	final static String submitDateString = "Submit_Date";
	final static String ownerString = "Owner";
	final static String typeString = "Test_Type";
	
	//this is the href link tag
	final static String defectLinkString = "#";

	HTTPDriver driver;
	Properties lProps=null;
	ScriptProperties props;
	
	/*private String url;
	private String urlPrefix;
	private String hostname;
	private String port;
	
	private String username;
	private String password;
	private String schema;
	private String welcome="welcome";
	private HTTPPostData data;//=driver.createPostData();
	*/

	
	public CQHttpTest() {
		try
		{
			init();
			//execute();
		}
		catch(Exception e)
		{
			if(Activator.DEBUG_ON)
				System.out.println(e.toString());
			e.printStackTrace();
		}
	}
		
	public Vector queryDefect(IBugSearchCriteria criteria) throws Exception{
		Vector ibuginfos = new Vector();//= new ArrayList<IBugInfo> ();
		
		CqDefectSearchCriteria cqCriteria = (CqDefectSearchCriteria) criteria;
		
		String defectId = cqCriteria.getNumber();
		
		ibuginfos = queryCQ(driver,props,"",defectId);
		return ibuginfos;
	}

	public void execute() throws TestFailureException,
			HTMLFailureException, FileNotFoundException,IOException {
		
		//String response = "";
		
		queryCQ(driver,props,"","15680");
		
		//response = logoutCQ(driver,props,response);
		
		//return response;
		
	}
	
	public void init() throws Exception {
		
		//loadConfig("httptest-apache.properties");
		loadConfig();
		//

		driver=createHTTPDriver();
		configureHttpDriver(driver);
		
		//HttpClient client=(HttpClient)(driver.getHttpClient());
		//client.getHttpConnectionManager().getParams().
		//
		//import org.apache.commons.httpclient.HttpClient;
		
		props=new ScriptProperties();
		FileInputStream input=null;
		//input=new FileInputStream("setup/CQPlugin.properties");
		//System.out.println("input is "+input);
		//props.load(input);
		props.load(Activator.CQ_CONF);
		//lProps=loadConfig("setup/CQPlugin.properties");
		/*
		url=props.getProperty("url");
		urlPrefix=props.getProperty("urlPrefix");
		hostname=props.getProperty("hostname");
		port=props.getProperty("port");
		
		username=props.getProperty("username");
		password=props.getProperty("password");
		schema=props.getProperty("schema");
		
		data=driver.createPostData();*/

	}
	
	protected HTTPDriver createHTTPDriver() throws Exception {
		String driverName=System.getProperty("com.ibm.httptest.HTTPDriver");
		return (HTTPDriver)(Class.forName(driverName).newInstance());
	}

	
	protected Properties loadConfig()
	  throws FileNotFoundException, IOException {
		//FileInputStream lInput=new FileInputStream(propFileName);
		Properties lProps=new Properties();
		//lProps.load(lInput);
		//lInput.close();
		lProps.load(Activator.HATJ_CONF);
		//lInput.close();

		Enumeration props=lProps.propertyNames();
		while (props.hasMoreElements()) {
			String key=(String)(props.nextElement());
			System.setProperty(key, lProps.getProperty(key));
		}
		return lProps;
	}
	
	protected void configureHttpDriver(HTTPDriver driver) {
		try {
			HttpClient client=(HttpClient)(driver.getHttpClient());

			String soTimeoutStr=System.getProperty("com.ibm.httptest.SoTimeout");
			if ((soTimeoutStr!=null) && (soTimeoutStr.length()>0)) {
				client.getHttpConnectionManager().getParams().setSoTimeout(Integer.parseInt(soTimeoutStr)*1000);
			}

			String connTimeoutStr=System.getProperty("com.ibm.httptest.ConnectionTimeout");
			if ((connTimeoutStr!=null) && (connTimeoutStr.length()>0)) {
				client.getHttpConnectionManager().getParams().setConnectionTimeout(Integer.parseInt(connTimeoutStr)*1000);
			}

			String connMgrTimeoutStr=System.getProperty("com.ibm.httptest.ConnectionManagerTimeout");
			if ((connMgrTimeoutStr!=null) && (connMgrTimeoutStr.length()>0)) {
				client.getParams().setConnectionManagerTimeout(Integer.parseInt(connTimeoutStr)*1000);
			}

			driver.setRecording(false, System.getProperty("com.ibm.httptest.ResultsPath"), null);
			//driver.
		} catch (Exception e) {
			System.err.println("configureHttpClient Exception: "+e.getMessage());
		}
		
		long waitTime=0, waitTime2=0;
		try {
			String waitTimeStr=System.getProperty("com.ibm.httptest.httpWaitTime");
			if ( (waitTimeStr!=null) && (waitTimeStr.length()>0) ) {
				if (waitTimeStr.indexOf(',')>0) {
					String times[]=waitTimeStr.split(",");
					waitTime=Long.valueOf(times[0]).longValue();
					waitTime2=Long.valueOf(times[1]).longValue();
				} else {
					waitTime=Long.valueOf(waitTimeStr).longValue();
				}
			}
		} catch (Exception e) {
		}
		if (waitTime>0) {
			((ApacheHTTPDriver)driver).setWaitTime(waitTime, waitTime2);
		}
		
		String writerName=System.getProperty("com.ibm.httptest.StatsWriter");
		if ((writerName!=null) && (writerName.length()>0)) {
			try {
				//statsWriter=(StatisticsWriter)(Class.forName(writerName).newInstance());
			} catch (Exception e) {
				System.err.println("Fail to initialize custom statistics writer: "+writerName);
			}
		}
	}

	
	public static void main(String args[]) {
		//if (true) return;
		CQHttpTest run=new CQHttpTest();
		try
		{
			//run.init();
			run.execute();
		}
		catch(Exception e)
		{
			//System.out.println(e.toString());
			e.printStackTrace();
		}
		//run.execute(driver,lProps,"");
	}
	
	private Vector queryCQ(HTTPDriver driver, ScriptProperties props,
	String prevResponse, String number) throws TestFailureException,
	HTMLFailureException {
		/* commented by Kevin, using Preference Insteade*/
		/*String url=props.getProperty("url");
		String urlPrefix=props.getProperty("urlPrefix");
		String hostname=props.getProperty("hostname");
		String port=props.getProperty("port");
		
		String username=props.getProperty("username");
		String password=props.getProperty("password");
		String schema=props.getProperty("schema");
		
		String db = //props.getProperty("userDb");
		*/
		
		String urlPrefix="http://";
		String hostname=Activator.getDefault().getPreferenceStore().getString(CqPreferenceConstants.PREF_HOST);
		String port=Activator.getDefault().getPreferenceStore().getString(CqPreferenceConstants.PREF_PORT);
		
		String username=Activator.getDefault().getPreferenceStore().getString(CqPreferenceConstants.PREF_USER_NAME);
		String password=Activator.getDefault().getPreferenceStore().getString(CqPreferenceConstants.PREF_PASSWORD);
		String schema=Activator.getDefault().getPreferenceStore().getString(CqPreferenceConstants.PREF_SCHEMA);
		
		String db = "DFECT";
		
		String url = urlPrefix + hostname + ":" + port + "/cqweb/login";
		
		Vector ibuginfos = new Vector();

		String response=prevResponse;
		if(Activator.DEBUG_ON)
			System.out.print("url:"+url);
		response=driver.sendGetRequest(url);
		if (!HTMLManager.hasKeyword(response, "User Name:")) {
			throw new HTMLFailureException("Failed to get Login fields", response);
		}

		url=urlPrefix+hostname+":"+port+HTMLManager.getCorrelationBoundary(response, "action=\"", "\" method=\"");//=\"post\"  name=\"formLogin\"");
		if(Activator.DEBUG_ON)
			System.out.println("url:"+url);

		HTTPPostData data=driver.createPostData();

		HTMLManager.saveHiddenValue(response, data);

		data.addParameter("username", username);
		data.addParameter("password", password);
		data.addParameter("schema", schema);
		data.addParameter("userDb", db);
		
		response=driver.postForm(url, data);



		String bannerUrl = HTMLManager.getCorrelationBoundary(response, "top.bannerFrame.document.location.href =  '", "';");//=\"post\"  name=\"formLogin\"");

		if(Activator.DEBUG_ON)
			System.out.println("bannerUrl is :"+bannerUrl);

		url=urlPrefix+hostname+":"+port+bannerUrl;

		response=driver.sendGetRequest(url);

		String mainServlet;

		if ((bannerUrl!=null) && (bannerUrl.indexOf('?') != -1))
		{
			mainServlet = bannerUrl.substring(0,bannerUrl.indexOf('?'));
		}
		else
		{
			mainServlet = bannerUrl;
		}

		String logoutUrl = urlPrefix+hostname+":"+port+ mainServlet + HTMLManager.getFlaggedAttribute(response, "Log Out", "href", true);

		String sessionIDStr = "rmsessionid=";
		String sessionID = logoutUrl.substring(logoutUrl.indexOf(sessionIDStr)+sessionIDStr.length());

		String mainURl = urlPrefix+hostname+":"+port+ mainServlet;
		String switchDBUrl = mainURl + "?USE_CASE=cq_dbswitch&dbid=DFECT";

		response=driver.sendGetRequest(switchDBUrl);

		response = driver.sendGetRequest(mainURl+"?command=GenerateMainFrame");

		String treeReponse = driver.sendGetRequest(mainURl+"?USE_CASE=px_tree");

		response = driver.sendGetRequest(mainURl+"?USE_CASE=cq_startup");

		response = driver.sendGetRequest(mainURl+"?command=GetSubmitEntityDefNames&rmsessionid="+sessionID);

		response = driver.sendGetRequest(mainURl+"?USE_CASE=cq_getworkspace_folder&dbid=projectroot&id=projectroot");

		String projectId = HTMLManager.getFlaggedAttribute(response, "Public Queries", "id", false);

		if(Activator.DEBUG_ON)
			System.out.println("projectId is :"+projectId);

		String dbid = HTMLManager.getCorrelationBoundary(response, "'"+projectId+"',dbid:'", "',pDbid:'projectroot'");

		response = driver.sendGetRequest(mainURl+"?USE_CASE=cq_getworkspace_folder&dbid="+dbid+"&id="+projectId);

		if(Activator.DEBUG_ON)
			System.out.println("dbid is :" + dbid);


		String dbid2 = HTMLManager.getFlaggedAttribute(response, "Defects By ID", "id", false);
		if(Activator.DEBUG_ON)
			System.out.println("dbid2::"+dbid2);

//		going to seach Defects By ID page
		response = driver.sendGetRequest(mainURl+"?command=GetPromptedFilterList&rmsessionid="+sessionID+"&dbid="+dbid2);


//		kick off CQ query

		Vector v = new Vector();
		v.addElement("command");

		v.addElement("calHiddenObj");
		v.addElement("calHiddenObj1");
		v.addElement("calHiddenObj2");
		v.addElement("fieldFiltersXML");

		data=driver.createPostData();

		HTMLManager.saveHiddenValueExclude(response, data, v);
		String defectNumber = number;//"15860";

		data.addParameter("fieldFiltersXML", "<FieldFilters><FieldFilter ID='Defect_ID'><Type>1</Type><CompOp>7</CompOp><Prompt>Enter Defect ID?</Prompt><Values><Value>"+defectNumber+"</Value></Values></FieldFilter><FieldFilter ID='Product'><Type>1</Type><CompOp>7</CompOp><Prompt>Enter Product?</Prompt><Values></Values></FieldFilter><FieldFilter ID='Product_Release'><Type>1</Type><CompOp>7</CompOp><Prompt>Enter Product_Release?</Prompt><Values></Values></FieldFilter></FieldFilters>");
		data.addParameter("command", "ExecuteQueryWithPromptValues");

		data.addParameter("filterValuesField", defectNumber);
		data.addParameter("betFilterValuesField1", "");
		data.addParameter("betFilterValuesField2", "");
		data.addParameter("calHiddenObj", "");
		data.addParameter("calHiddenObj1", "");
		data.addParameter("calHiddenObj2", "");

		//selectedFilters

		data.addParameter("selectedFilters", "2");
		data.addParameter("operationsList", "7");
		
		String str = "?command=GetRecords&rmsessionid="+sessionID+"&dbid="+dbid2+"&qid="+dbid2;

		response=driver.postForm(mainURl, data);

		response=driver.sendGetRequest(mainURl+str);
		
		String htmlTableTag;//=HTMLManager.getCorrelationBoundary(response, "top.contentFrame.location.href = \"main", "\";");
		
		
		//HTMLManager.getAllCorrelationInclude(html, instance)
		String tableLb = "<table summary=\"\" cellpadding=\"0\" cellspacing=\"0\" border=\"1\" width=\"100%\">";
		String tableRb = "</table>";
		str=HTMLManager.getCorrelationBoundary(response, tableLb, tableRb);
		
		htmlTableTag = tableLb+str+tableRb;
		
		String rowHtml = HTMLManager.getCorrelationBoundary(htmlTableTag, "<tr>", "</tr>");
		
		//System.out.println("first row is :"+rowHtml);
		List heading = processTableRow(rowHtml);
		
		if(Activator.DEBUG_ON) {
			System.out.println("heading is");
			System.out.println(heading.toString());
		}
		
		htmlTableTag = htmlTableTag.substring(htmlTableTag.indexOf(rowHtml)+rowHtml.length());
		
		//List results = new ArrayList();

		//List<CqDefectInfo> ibuginfos = new ArrayList<CqDefectInfo> ();
		int idIndex = -1;
		int headIndex = -1;
		int subIndex = -1;
		int servIndex = -1;
		int stateIndex = -1;
		int dateIndex = -1;
		int ownerIndex = -1;
		int typeIndex = -1;
		int linkIndex = -1;

		idIndex = heading.indexOf(idString);
		headIndex = heading.indexOf(headString);
		subIndex = heading.indexOf(submitterString);
		servIndex = heading.indexOf(severityString);
		stateIndex = heading.indexOf(stateString);
		dateIndex = heading.indexOf(submitDateString);
		
		ownerIndex = heading.indexOf(ownerString);
		typeIndex = heading.indexOf(typeString);
		linkIndex = heading.indexOf(defectLinkString);
		

		while (htmlTableTag.indexOf("<tr>")!=-1)
		{
			rowHtml = HTMLManager.getCorrelationBoundary(htmlTableTag, "<tr>", "</tr>");
			htmlTableTag = htmlTableTag.substring(htmlTableTag.indexOf(rowHtml)+rowHtml.length());
			
			List nextline = processTableRow(rowHtml);
			
			if(Activator.DEBUG_ON) {
				System.out.println("nextline is");
				System.out.println(nextline.toString());
			}
			//get the defect Number from this line
			//get the index of the defect
			
			if (idIndex != -1) {
				str = (String) nextline.get(idIndex);
				if (str!=null || !str.trim().equals(""))
				{	
					CqDefectInfo bugInfo = new CqDefectInfo(str);
					//set the abstract
					bugInfo.setAbstractStr((String) nextline.get(headIndex));
					//set submitter
					bugInfo.setOriginator((String) nextline.get(subIndex));
					//set Severity
					bugInfo.setSeverity(BugSeverity.getBugSeverityFromCode(((String)nextline.get(servIndex)).substring(2)));
					if(Activator.DEBUG_ON)
						System.out.println("Severity is: " + ((String)nextline.get(servIndex)).substring(2));
					//set State
					//bugInfo.setState(BugState.(String) nextline.get(stateIndex));
					bugInfo.setState(BugState.getBugStateFromCode((String)nextline.get(stateIndex)));
					if(Activator.DEBUG_ON)
						System.out.println("State is: " + nextline.get(stateIndex));
					//set Defect Owner
					bugInfo.setOwner((String) nextline.get(ownerIndex));
					//set test Type
					bugInfo.setTestType((String) nextline.get(typeIndex));
					
					//set the defect link information
					bugInfo.setDefectlink(getLink((String) nextline.get(linkIndex)));
					
					if(Activator.DEBUG_ON)
						System.out.println("bug link is :"+ bugInfo.getDefectlink());
					
					ibuginfos.add(bugInfo);
					
				}
				continue;
			}
			//String 
			
			if(Activator.DEBUG_ON)
				System.out.println("next row is :"+rowHtml);

			//results.add(nextline);

		}
	
		if(Activator.DEBUG_ON)
			System.out.println("logoutUrl is :"+logoutUrl);
		response=driver.sendGetRequest(logoutUrl);
		

		
		return ibuginfos;
		
	}
	
	public String viewDefectDetail(String linkHref) throws TestFailureException, HTMLFailureException{
		
		String urlPrefix="http://";
		String hostname=Activator.getDefault().getPreferenceStore().getString(CqPreferenceConstants.PREF_HOST);
		String port=Activator.getDefault().getPreferenceStore().getString(CqPreferenceConstants.PREF_PORT);
		
		String username=Activator.getDefault().getPreferenceStore().getString(CqPreferenceConstants.PREF_USER_NAME);
		String password=Activator.getDefault().getPreferenceStore().getString(CqPreferenceConstants.PREF_PASSWORD);
		String schema=Activator.getDefault().getPreferenceStore().getString(CqPreferenceConstants.PREF_SCHEMA);
		
		String db = "DFECT";
		
		//String url=props.getProperty("url");
		String url = urlPrefix + hostname + ":" + port + "/cqweb/login";
		
		String response="";
		HTTPPostData data=driver.createPostData();
		if(Activator.DEBUG_ON)
			System.out.print("url:"+url);
		response=driver.sendGetRequest(url);
		if (!HTMLManager.hasKeyword(response, "User Name:")) {
			throw new HTMLFailureException("Failed to get Login fields", response);
		}

		url=urlPrefix+hostname+":"+port+HTMLManager.getCorrelationBoundary(response, "action=\"", "\" method=\"");//=\"post\"  name=\"formLogin\"");

		
		HTMLManager.saveHiddenValue(response, data);
		//.saveHiddenValueExclude(form, data, v);
		//log in the system
		data.addParameter("username", username);
		data.addParameter("password", password);
		data.addParameter("schema", schema);
		data.addParameter("userDb", db);
		//System.out.println(data.toString());
		
		//for some reasons, it returns the page of frames after login
		response=driver.postForm(url, data);
		
		String bannerUrl = HTMLManager.getCorrelationBoundary(response, "top.bannerFrame.document.location.href =  '", "';");//=\"post\"  name=\"formLogin\"");

		if(Activator.DEBUG_ON)
			System.out.println("bannerUrl is :"+bannerUrl);
		
		url=urlPrefix+hostname+":"+port+bannerUrl;
		
		response=driver.sendGetRequest(url);
		
		String mainServlet;
		
		if ((bannerUrl!=null) && (bannerUrl.indexOf('?') != -1))
		{
			mainServlet = bannerUrl.substring(0,bannerUrl.indexOf('?'));
		}
		else
		{
			mainServlet = bannerUrl;
		}
		
		String logoutUrl = urlPrefix+hostname+":"+port+ mainServlet + HTMLManager.getFlaggedAttribute(response, "Log Out", "href", true);
		
		if(Activator.DEBUG_ON)
			System.out.println("logout URL is :"+logoutUrl);
		
		//response=selectCQDatabase();
		//select CQ Database
		
		String sessionIDStr = "rmsessionid=";
		String sessionID = logoutUrl.substring(logoutUrl.indexOf(sessionIDStr)+sessionIDStr.length());
		
		String mainURl = urlPrefix+hostname+":"+port+ mainServlet;
		//start the db
		String switchDBUrl = mainURl + "?USE_CASE=cq_dbswitch&dbid=DFECT";
		
		response=driver.sendGetRequest(switchDBUrl);

		//response = driver.sendGetRequest(mainURl+"?command=GenerateMainFrame");

		//String treeReponse = driver.sendGetRequest(mainURl+"?USE_CASE=px_tree");
		
		response = driver.sendGetRequest(mainURl+"?USE_CASE=cq_startup");
		
		//response = driver.sendGetRequest(mainURl+"?command=GetSubmitEntityDefNames&rmsessionid="+sessionID);

		//response = driver.sendGetRequest(mainURl+"?USE_CASE=cq_getworkspace_folder&dbid=projectroot&id=projectroot");
		
		//
		
		//get the detail of the defect
		
		url=mainURl + linkHref+"&rmsessionid="+sessionID;//urlPrefix+hostname+":"+port+"/"+linkHref;

		if(Activator.DEBUG_ON)
			System.out.println("defect detail url is :"+url);
		//String detail=driver.sendGetRequest(logoutUrl);
		String detail=driver.sendGetRequest(url);

		//log out the system
		response=driver.sendGetRequest(logoutUrl);
		
		return detail;
		
	}
	
	private List processTableRow(String rowHtml) {
		List rowList = new ArrayList();
		//StringTokenizer st = new StringTokenizer(rowHtml.trim(), "</td>");
		// Iterate over all of the attributes
		if (rowHtml==null)
			return rowList;
		rowHtml = rowHtml.trim();
		while( rowHtml.indexOf("</td>")!=-1 )
		{
		  String tmpStr = rowHtml.substring(0,rowHtml.indexOf("</td>"));
		  
		  if (tmpStr.indexOf('>')!=-1)
		  {
			  tmpStr = tmpStr.substring(tmpStr.indexOf('>')+1);
		  }
	  
		  //remove all html tag &nbsp;
		  tmpStr = tmpStr.replaceAll("&nbsp;", "").trim();
		  
		  if(Activator.DEBUG_ON)
			  System.out.print("processed token:"+tmpStr+" ");
		  
		  rowList.add(tmpStr);
		  
		  rowHtml = rowHtml.substring(rowHtml.indexOf("</td>")+"</td>".length()).trim();
		}
		//System.out.println("");
		
		return rowList;
	}
	
	private String logoutCQ(HTTPDriver driver, ScriptProperties props,
			String prevResponse) throws TestFailureException,
			HTMLFailureException {
				
				String url=props.getProperty("url");
			
				String response=prevResponse;
				String welcome="welcome";

				response=driver.sendGetRequest(url);
				if (!HTMLManager.hasKeyword(response, "User Name:")) {
					throw new HTMLFailureException("Failed to get Login fields", response);
				}

				//url=""//urlPrefix+hostname+":"+port+HTMLManager.getCorrelationBoundary(response, "action=\"", "\" name=\"LoginForm\"");
				HTTPPostData data=driver.createPostData();
				//data.addParameter("username", username);
				//data.addParameter("password", password);
				response=driver.postForm(url, data);
				
				if (!HTMLManager.hasKeyword(response, welcome)) {
					throw new HTMLFailureException("Failed to find: "+welcome, response);
				}

				return response;
				
	}
	
	private String getLink(String tempStr) {
			String hrefTag = "href=\"";
			int index = -1;
			if(tempStr==null || "".equals(tempStr.trim())){
				return tempStr;
			}
			index = tempStr.indexOf(hrefTag);
			if (index == -1) {
				return tempStr;
			}
			tempStr = tempStr.substring(index+hrefTag.length());
			//get rid of the rest of the "
			index = tempStr.indexOf('\"');
			
			if (index == -1) {
				return tempStr;
			}
			tempStr = tempStr.substring(0,index);
			
			//get rid of main tag
			index = tempStr.indexOf("main");
			
			if (index == -1) {
				return tempStr;
			}
			tempStr = tempStr.substring(index+"main".length());
			
			//get rid of sessionid
			index = tempStr.indexOf("&rmsessionid");

			if (index == -1) {
				return tempStr;
			}
			tempStr = tempStr.substring(0, index);

			if(Activator.DEBUG_ON)
				System.out.println("link is :"+tempStr);
			return tempStr;
			
	}
	

}
